package com.devinlee.designpatterns.proxy.dynamicproxy;

import com.devinlee.designpatterns.proxy.Subject;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 动态代理-自定义编织流程
 */
public class MyInvocationHandler implements InvocationHandler {

    // 拦截器的实现
    private Interceptor interceptor;
    // 真实对象
    private Subject realSubject;

    public MyInvocationHandler(Interceptor interceptor, Subject realSubject) {
        this.interceptor = interceptor;
        this.realSubject = realSubject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
        // 实现执行前增强
        interceptor.before();
        // 反射调用真实对象
        Object res = method.invoke(realSubject, args);
        // 实现执行后增强
        interceptor.before();
        return res;
    }
}
